package com.codesuc.aichat.aiAgent.strategy.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codesuc.aichat.aiAgent.config.AIConfig;
import com.codesuc.aichat.aiAgent.constant.AIAgentConstant;
import com.codesuc.aichat.aiAgent.request.ChatRequest;
import com.codesuc.aichat.aiAgent.response.ChatResponse;
import com.codesuc.aichat.aiAgent.strategy.AIService;
import com.codesuc.aichat.chatHistory.service.ChatHistoryService;
import com.codesuc.aichat.enums.CodeSucErrorEnum;
import com.codesuc.aichat.exception.CodeSucException;
import com.codesuc.aichat.role.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ZhangGongMing
 * @CreateTime: 2025/9/23 23:21
 * @description: 七牛云 AI 实现类
 * @Version: 1.0
 */
@Slf4j
@Service
public class QiNiuAIServiceImpl implements AIService {

    @Autowired
    private AIConfig config;
    @Autowired
    private ChatHistoryService chatHistoryService;
    @Autowired
    private RoleService roleService;

    /**
     * 获取 AI 服务商名称
     *
     * @return 服务商名称
     */
    @Override
    public String getServiceName() {
        return AIAgentConstant.QINIU;
    }

    /**
     * 聊天
     *
     * @param request 请求参数
     * @return 响应结果
     */
    @Override
    public Flux<ChatResponse> chat(ChatRequest request) {
        AIConfig.Qiniu qiniu = config.getQiniu();

        if (qiniu == null) {
            throw new CodeSucException(CodeSucErrorEnum.NOT_FOUND_AI_SERVICE_CONFIGURATION);
        }

        // 获取配置项
        String apiKey = qiniu.getApiKey();
        String chatUrl = qiniu.getChatUrl();
        String model = request.getModel();
        if (StrUtil.isBlank(model)) {
            // 如果传了用用户选择的，没有传用默认的
            model = qiniu.getModel();
        }

        // TODO 加入用户历史消息

        // TODO 加入角色设定提示词


        // 构建请求体
        Map<String, Object> params = new HashMap<>();
        params.put("model", model);
        params.put("messages", request.getMessageList());
        params.put("stream", request.getIsStream());


        WebClient webClient = WebClient.builder()
                .baseUrl(chatUrl)
                .defaultHeader("Authorization", "Bearer " + apiKey)
                .defaultHeader("Content-Type", "application/json")
                .build();
        return Flux.create(sink -> {
            webClient.post()
                    .uri(chatUrl)
                    .bodyValue(params)
                    .retrieve()
                    .bodyToFlux(String.class)
                    .subscribe(data -> {
                                try {
                                    // 处理流式响应（SSE）
                                    if (request.getIsStream()) {
                                        if (!"[DONE]".equals(data)) {
                                            JSONObject jsonObject = JSONObject.parseObject(data);
                                            if (jsonObject.containsKey("choices") && !"stop".equals(jsonObject.getString("finish_reason"))) {
                                                JSONObject choice = jsonObject.getJSONArray("choices").getJSONObject(0);
                                                String delta = choice.getJSONObject("delta").getString("content");

                                                log.info("stream response : {}", data);
                                                ChatResponse chatResponse = new ChatResponse();
                                                chatResponse.setSuccess(true);
                                                chatResponse.setContent(delta);
                                                sink.next(chatResponse);
                                            }
                                        } else {
                                            // 收到[DONE]标记，完成流
                                            sink.complete();

                                            // 添加历史记录到表中
                                        }
                                    } else {
                                        // 处理非流式响应（完整JSON）
                                        JSONObject jsonObject = JSONObject.parseObject(data);
                                        if (jsonObject.containsKey("choices")) {
                                            JSONArray choices = jsonObject.getJSONArray("choices");
                                            if (choices.size() > 0) {
                                                JSONObject choice = choices.getJSONObject(0);
                                                JSONObject message = choice.getJSONObject("message");
                                                String content = message.getString("content");

                                                log.info("non-stream response : {}", data);
                                                ChatResponse chatResponse = new ChatResponse();
                                                chatResponse.setSuccess(true);
                                                chatResponse.setContent(content);
                                                sink.next(chatResponse);
                                            }
                                        }
                                        // 完成流
                                        sink.complete();
                                    }
                                } catch (Exception e) {
                                    log.error("处理响应时发生错误: {}", e.getMessage(), e);
                                    sink.error(e);
                                }
                            },
                            error -> {
                                // 处理错误
                                log.error("处理流时发生错误: {}", error.getMessage(), error);
                                sink.error(error);
                            },
                            () -> {
                                // 正常完成流
                                sink.complete();
                            });
        });
    }

    /**
     * 音频转文字
     *
     */
    @Override
    public String audioASR() {
        return "";
    }

    /**
     * 停止音频转文字
     */
    @Override
    public void stopAudioASR() {

    }

    /**
     * 语音合成
     *
     * @param text 文本
     */
    @Override
    public void audioTTS(String text, Long roleId) {

    }

    /**
     * 异步调用保存聊天记录
     * TODO 待开发
     */
    private void asyncSaveChatHistory() {

    }

}
